package com.zhoug.ocr.textin.http.core;

import com.zhoug.common.content.Optional;
import com.zhoug.common.http.ApiException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

/**
 * @Author: zhoug
 * @Date: 2023/2/20
 * @Description:
 */
public class TextInResponseTransformer {
    public static <T> ObservableTransformer<TextInResponse<T>, Optional<T>> handleResult() {
        return upstream ->
                upstream.onErrorResumeNext(new ErrorResumeFunction<>())
                        .flatMap(new ResponseFunction<>());
    }


    /**
     * 请求结果预处理,代码不是BaseResponse.STATUS_SUCCESS的返回异常
     * @param <T>
     */
    private static class ResponseFunction<T> implements Function<TextInResponse<T>, ObservableSource<Optional<T>>> {


        @Override
        public ObservableSource<Optional<T>> apply(TextInResponse<T> tBaseModel) throws Exception {
            if(tBaseModel!=null){
                if(tBaseModel.getCode()==TextInResponse.STATUS_SUCCESS){
                    T data = tBaseModel.getResult();
                    return Observable.just(Optional.create(data));
                }else{
                    return Observable.error(new Exception(tBaseModel.getMessage()));
                }
            }
            return  Observable.error(new Exception("null"));
        }
    }


    /**
     * 异常处理
     *
     * @param <T>
     */
    private static class ErrorResumeFunction<T> implements Function<Throwable, ObservableSource<? extends TextInResponse<T>>> {

        @Override
        public ObservableSource<? extends TextInResponse<T>> apply(Throwable throwable) throws Exception {
//            MyUncaughtExceptionHandler.getInstance().writeExceptionToFile(throwable);
            return Observable.error(ApiException.handleException(throwable));

        }
    }
}
